package org.lemon.cla.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.lemon.cla.enums.HttpStatusEnum;
import org.lemon.cla.dto.response.ResponseResult;
import org.lemon.cla.serviceImp.CosUploadServiceImpl;
import org.lemon.cla.util.MockMultipartFile; // 导入我们单独列出的 MockMultipartFile
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional; // 导入Optional

import org.lemon.cla.exception.BusinessException; // 导入自定义业务异常

@RestController
@RequestMapping("/api")
@Slf4j
@Tag(name = "文件上传接口", description = "提供富文本编辑器图片上传等文件上传服务")
public class UploadController {

    private final CosUploadServiceImpl cosUploadServiceImpl;

    // 定义允许的图片和HTML内容类型
    private static final List<String> ALLOWED_IMAGE_TYPES = Arrays.asList(
            MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE, MediaType.IMAGE_GIF_VALUE,
            "image/bmp", "image/webp"
    );
    private static final List<String> ALLOWED_HTML_TYPES = Arrays.asList(
            MediaType.TEXT_HTML_VALUE
    );

    private static final long MAX_IMAGE_SIZE_BYTES = 512 * 1024; // 512 KB
    private static final long MAX_HTML_SIZE_BYTES = 2 * 1024 * 1024; // 2 MB

    public UploadController(CosUploadServiceImpl cosUploadServiceImpl) {
        this.cosUploadServiceImpl = cosUploadServiceImpl;
    }

    @PostMapping(value = "/upload_image", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) // 修改了路径和 consumes
    @Operation(summary = "上传文件", description = "用于上传常见图片文件或富文本HTML，返回文件URL",
            security = @SecurityRequirement(name = "bearerAuth"))
    public ResponseResult<Map<String, String>> uploadFile( // 修改了方法名
                                                           @Parameter(description = "要上传的文件 (图片或HTML)", required = true,
                                                                   content = @Content(mediaType = MediaType.MULTIPART_FORM_DATA_VALUE,
                                                                           schema = @Schema(type = "string", format = "binary")))
                                                           @RequestParam("file") MultipartFile file) throws IOException { // IOException 抛出，由GlobalExceptionHandler处理

        String contentType = Optional.ofNullable(file.getContentType())
                .orElseThrow(() -> new BusinessException(HttpStatusEnum.UNSUPPORTED_TYPE.getCode(), "无法识别文件类型。")); // 抛出 BusinessException

        String originalFilename = Optional.ofNullable(file.getOriginalFilename()).orElse("uploaded_file");
        log.info("接收文件: {}，内容类型: {}", originalFilename, contentType);

        Map<String, String> data = new HashMap<>();
        String fileUrl;

        // --- 1. 根据文件类型处理 ---
        if (ALLOWED_IMAGE_TYPES.contains(contentType)) {
            // --- 2. 如果是图片，压缩成webp再上传 ---
            BufferedImage originalImage = Optional.ofNullable(ImageIO.read(file.getInputStream()))
                    .orElseThrow(() -> new BusinessException(HttpStatusEnum.UNSUPPORTED_TYPE.getCode(), "文件不是有效的图片格式。")); // 抛出 BusinessException

            ByteArrayOutputStream webpOutputStream = new ByteArrayOutputStream();
            ImageIO.write(originalImage, "webp", webpOutputStream); // 写入webp格式

            byte[] webpImageBytes = webpOutputStream.toByteArray();

            // --- 3. 图片压缩后仍然大于512kb的不上传 ---
            if (webpImageBytes.length > MAX_IMAGE_SIZE_BYTES) {
                throw new BusinessException(HttpStatusEnum.UNSUPPORTED_TYPE.getCode(), "图片压缩后仍然大于" + (MAX_IMAGE_SIZE_BYTES / 1024) + "KB，无法上传。"); // 抛出 BusinessException
            }

            // 从压缩后的WebP字节创建一个新的MultipartFile
            MultipartFile webpFile = new MockMultipartFile(
                    file.getName(),
                    originalFilename.substring(0, originalFilename.lastIndexOf(".")) + ".webp",
                    "image/webp",
                    webpImageBytes
            );

            fileUrl = cosUploadServiceImpl.uploadFile(webpFile, "2025shixun/");
            data.put("url", fileUrl);
            data.put("location", fileUrl);
            return ResponseResult.success(data);

        } else if (ALLOWED_HTML_TYPES.contains(contentType)) {
            // --- 4. html大于2mb的不上传 ---
            if (file.getSize() > MAX_HTML_SIZE_BYTES) {
                throw new BusinessException(HttpStatusEnum.UNAUTHORIZED.getCode(), "HTML文件大于" + (MAX_HTML_SIZE_BYTES / (1024 * 1024)) + "MB，无法上传。"); // 抛出 BusinessException
            }
            fileUrl = cosUploadServiceImpl.uploadFile(file, "2025shixun/");
            data.put("url", fileUrl);
            data.put("location", fileUrl);
            return ResponseResult.success(data);
        } else {
            // 如果既不是允许的图片类型也不是允许的HTML类型
            throw new BusinessException(HttpStatusEnum.UNSUPPORTED_TYPE.getCode(), "不支持的文件类型。只接受常见图片文件 (JPEG, PNG, GIF, BMP, WebP) 和富文本HTML文件。"); // 抛出 BusinessException
        }
    }
}
